package cn.udrm.elasticsearch.web;

import cn.udrm.elasticsearch.model.Article;
import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
@Slf4j
public class Controller {

    @Autowired
    private JestClient jestClient;

    @RequestMapping(value = "/search/{keyword}",method = RequestMethod.GET)
    @ApiOperation(value = "全部字段搜索关键字",notes = "es验证")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "keyword",value = "全文检索关键字",required = true,paramType = "path",dataType = "String")
    )
    public List search(@PathVariable String keyword){
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.queryStringQuery(keyword));

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //path属性高亮度
        HighlightBuilder.Field highlightPath = new HighlightBuilder.Field("path");
        highlightPath.highlighterType("unified");
        highlightBuilder.field(highlightPath);
        //title字段高亮度
        HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("title");
        highlightTitle.highlighterType("unified");
        highlightBuilder.field(highlightTitle);
        //content字段高亮度
        HighlightBuilder.Field highlightContent = new HighlightBuilder.Field("content");
        highlightContent.highlighterType("unified");
        highlightBuilder.field(highlightContent);

        //高亮度配置生效
        searchSourceBuilder.highlighter(highlightBuilder);

        log.info("搜索条件{}",searchSourceBuilder.toString());

        //构建搜索功能
        Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex( "gf" ).addType( "news" ).build();
        try {
            //执行
            SearchResult result = jestClient.execute( search );
            return result.getHits(Article.class);
        } catch (IOException e) {
            log.error("{}",e.getLocalizedMessage());
        }
        return null;
    }
}
